package com.share.two.bio.文件上传;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	
	@SuppressWarnings("resource")
	public static void main(String[] args) throws IOException {
		ServerSocket server = new ServerSocket(54321);
		System.out.println("服务器启动。。。");
		
		while (true) {
			final Socket socket = server.accept();
			
			Thread t = new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						InputStream in = socket.getInputStream();
						BufferedReader br = new BufferedReader(new InputStreamReader(in));
						PrintStream ps = new PrintStream(socket.getOutputStream());
						
						String fileName = br.readLine();
						
						File dir = new File("server");
						dir.mkdir();
						File file = new File(dir, fileName);
						if (file.exists()) {
							System.out.println("该文件已存在");
							ps.println("存在");
							socket.close();
							return;
						} else {
							System.out.println("该文件不存在");
							ps.println("不存在");
						}
						
						FileOutputStream fo = new FileOutputStream(file);
						byte[] arr = new byte[8*1024];
						int len;
						while ((len = in.read(arr)) != -1) {
							fo.write(arr, 0, len);
						}
						System.out.println(fileName + "上传成功。。。");
						fo.close();
						socket.close();
						
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}, "server");
			t.start();
			
		}
		
	}

}
